<template>
  <div class="app-main-container">
    <div class="app-main-title">摄像头管理</div>
    <div class="doumee-filter">
      <el-input v-model="filters.cameraName" placeholder="输入监控点名称" clearable />
      <el-select v-model="filters.status" placeholder="选择使用状态" clearable>
        <el-option
          v-for="item in statusList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" @click="getList(1)" v-preventReClick>查找</el-button>
      <el-button @click="clearList" v-preventReClick>清空</el-button>
    </div>
    <el-tabs v-model="active" @tab-click="handleClick">
      <el-tab-pane v-for="(tab, i) in tabList" :key="tab.id" :label="tab.manufacturer" :name="i.toString()">
        <div class="tips">
          <div class="tips_box">
            <div><p>监控点总数</p><p>{{ info.totalOne || info.totalTwo?info.totalOne + info.totalTwo : 0 }}</p></div>
            <div class="tips_xian" />
            <div><p>在线率</p><p>{{ info.totalps?info.totalps :'100%' }}</p></div>
          </div>
          <div class="tips_box">
            <div><p>在线</p><p>{{ info.totalOne ?info.totalOne :0 }}</p></div>
            <div class="tips_xian" />
            <div><p>离线</p><p>{{ info.totalTwo?info.totalTwo :0 }}</p></div>
          </div>
        </div>
        <div class="doumee-filter manufacturer">
          <div><el-button type="info" @click="showZhpzBtn">账号配置</el-button>
            <el-button type="primary" @click="tbBtn">同步</el-button>
            <el-button type="primary" @click="cjxz">监控插件下载</el-button> </div>
          <div class="detail" @click="manufacturerDetail"><i class="el-icon-warning-outline" /> 厂商说明</div>
        </div>
        <el-table
          v-loading="listLoading"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          :header-row-class-name="'table-header'"
          class="doumee-element-table"
        >
          <el-table-column
            align="center"
            label="设备编号"
            prop="id"
            min-width="300"
          />
          <el-table-column
            align="center"
            label="监控点名称"
            prop="cameraName"
            min-width="200"
          />
          <el-table-column align="center" label="状态" min-width="150" prop="status">
            <template slot-scope="scope">
              {{ scope.row.status == "0" ? "离线" : "在线" }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="监控点类型"
            prop="cameraType"
            min-width="150"
          >
            <template slot-scope="scope">
              {{ scope.row.cameraType == "0" ? "枪机" : scope.row.cameraType == "1" ? "半球" : scope.row.cameraType == "2" ? "枪机":scope.row.cameraType == "3" ? "快球":scope.row.cameraType == "4" ? "云台枪机":'' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="200">
            <template slot-scope="scope">
              <div class="flex-cc">
                <el-button v-if="functors && functors[0] == '1'" type="text" @click="add(0, scope.row)">实时预览</el-button>
                <el-button v-if="functors && functors[1] == '1'" type="text" @click="showTimeBtn(scope.row)">录像回放</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="flex-cc doumee-pagination">
          <el-pagination
            background
            hide-on-single-page
            layout="prev, pager, next"
            :current-page.sync="pagination.page"
            :total="total"
            @current-change="getList"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      title="选择回放时间"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      :visible.sync="showTime"
      width="600px"
    >
      <div class="xzsj">
        <el-date-picker
          v-model="param.startTime"
          popper-class="rqtc"
          type="datetime"
          placement="top"
          placeholder="选择开始日期时间"
          :picker-options="pickerBeginOption(1)"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
        />
        <div class="division-line">-</div>
        <el-date-picker
          v-model="param.endTime"
          popper-class="rqtc"
          type="datetime"
          placement="top"
          placeholder="选择结束日期时间"
          :picker-options="pickerBeginOption(2)"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelTime">取消</el-button>
        <el-button type="primary" @click="confirmTime" v-preventReClick>确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="playMode==0 ? '实时预览' : '录像回放'"
      :visible.sync="showJk"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      width="80%"
      @close="gbVideo"
    >
      <div ref="playWndBox" class="hksp">
        <!-- 视频数据站位 -->
        <div
          id="playWnd"
          class="playWnd"
          :style="{ height: playWndHeight + 'px', width: playWndWidth + 'px' }"
        />
      </div></el-dialog>
    <el-dialog
      title="账号配置"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      :visible.sync="showZhpz"
    >
      <el-form ref="ruleForm" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="IP地址：" prop="ipAddre">
          <el-input v-model="form.ipAddre" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="端口号：" prop="port">
          <el-input v-model="form.port" placeholder="请输入端口号" />
        </el-form-item>
        <el-form-item label="AppKey：" prop="appKey">
          <el-input v-model="form.appKey" placeholder="请输入AppKey" />
        </el-form-item>
        <el-form-item label="AppSecret：" prop="appSecret">
          <el-input v-model="form.appSecret" placeholder="请输入AppSecret" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showZhpz = false">取消</el-button>
        <el-button type="primary" @click="onSubmit" v-preventReClick>确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { monitoryList, getSoftDownLoad, monitory, manufacturerList, manufacturerDetail, sxtaccountConfig, sxtaccountConfigInfo } from '@/api'
import { parseTime } from '@/utils'
import store from '@/store'
export default {
  data() {
    return {
      modalDialog: store.getters.dialog,
      info: {},
      tabList: [],
      functors: [],
      active: '0',
      pagination: {
        page: 1,
        rows: 10
      },
      total: 0,
      list: [],
      listLoading: true,
      statusList: [
        { value: '1', label: '在线' },
        { value: '0', label: '离线' }
      ],
      filters: {},
      param: {},
      playWndHeight: '',
      // 视频盒子的宽度
      playWndWidth: '',
      oWebControl: null,
      initCount: 0,
      pubKey: '',
      playMode: 1, // 0 预览 1回放
      cameraIndexCode: '', // 监控点编号
      objData: {},
      showJk: false,
      showTime: false,
      showZhpz: false,
      form: {},
      rules: {
        ipAddre: [
          { required: true, message: '请输入IP地址', trigger: 'blur' }
        ],
        port: [
          { required: true, message: '请输入端口号', trigger: 'blur' }
        ],
        appKey: [
          { required: true, message: '请输入AppKey', trigger: 'blur' }
        ],
        appSecret: [
          { required: true, message: '请输入AppSecret', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
  },
  destroyed() {
    if (this.oWebControl != null) {
      // 先让窗口隐藏，规避可能的插件窗口滞后于浏览器消失问题
      this.oWebControl.JS_HideWnd()
      // 销毁当前播放的视频
      this.oWebControl.JS_RequestInterface({ funcName: 'destroyWnd' })
      // 断开与插件服务连接
      this.oWebControl.JS_Disconnect()
    }
  },
  created() {
    this.tomanufacturerList()
  },
  methods: {
    showZhpzBtn() {
      this.pzDetail()
      this.showZhpz = true
    },
    pzDetail() {
      // const that = this
      sxtaccountConfigInfo({
        param: {
          manufacturerId: this.tabList[this.active].id,
          venueId: sessionStorage.getItem('venueId')
        }
      },
      sessionStorage.getItem('venueId'))
        .then(res => {
          if (res.errorCode === '000000') {
            if (res.record && res.record.accountParm) {
              const obj = res.record.accountParm
              this.form = obj
              this.objData = {
                appkey: obj.appKey,
                ip: obj.ipAddre,
                port: Number(obj.port),
                secret: obj.appSecret
              }
            }
          }
        }).catch(err => {
          console.log(err)
        })
    },
    onSubmit() {
      // const that = this
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const param = {}
          param.venueId = sessionStorage.getItem('venueId')
          param.manufacturerId = this.tabList[this.active].id
          param.accountParm = this.form
          sxtaccountConfig({
            param
          })
            .then(res => {
              if (res.errorCode === '000000') {
                this.$message.success('账号配置成功')
                this.showZhpz = false
                this.pzDetail()
              }
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    tbBtn() {
      monitory({
        param: {
          manufacturerId: this.tabList[this.active].id,
          venueId: sessionStorage.getItem('venueId')
        }
      }, sessionStorage.getItem('venueId'))
        .then(res => {
          if (res.errorCode === '000000') { this.getList(1) }
        })
        .catch(err => {
          console.log(err)
        })
    },
    pickerBeginOption(e) {
      const date = new Date()
      const minutes = date.getMinutes()
      // h和m 是将日期只取时分
      const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
      const m = (minutes < 10 ? '0' + minutes : minutes)
      // pickerDate 判断当前选择时间是否等于上条数据时间
      // 若等于时，限制时间从00：00：00 - 上条数据开始时间，不等于时，24小时可选
      let str = ''
      if (e === 1) { str = this.param.startTime } else { str = this.param.endTime }
      const pickerDate = date.toDateString() === new Date(str).toDateString()
      return { disabledDate: (time) => {
        return time.getTime() > new Date().getTime()
      },
      selectableRange: pickerDate ? '00:00:00 -' + h + m + ':00' : '00:00:00 - 23:59:59' }
    },
    handleClick(e) {
      this.getList(1)
      this.pzDetail()
    },
    clearList() {
      this.filters = {}
      this.getList(1)
    },
    getList(page) {
      const { filters, pagination } = this
      const venueId = sessionStorage.getItem('venueId')
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      pagination.firstQueryTime = parseTime(new Date())
      monitoryList({
        pagination,
        param: {
          venueId,
          ...filters,
          manufacturerId: this.tabList[this.active].id
        }
      }, sessionStorage.getItem('venueId'))
        .then(res => {
          this.list = res.recordList
          this.total = res.totalCount
          this.info = res
          this.listLoading = false
        }).catch(() => {
          this.listLoading = false
        })
    },
    tomanufacturerList() {
      manufacturerList({ param: { type: '3' }}, sessionStorage.getItem('venueId')).then(res => {
        this.tabList = res.recordList
        this.functors = res.recordList[0].functors || []
        this.getList(1)
        this.pzDetail()
      }).catch(err => {
        console.log(err)
      })
    },
    cjxz() {
      getSoftDownLoad({ param: { manufacturerId: this.tabList[this.active].id }}, sessionStorage.getItem('venueId')).then(res => {
        if (res.errorCode === '000000') {
          window.open(res.record, '_blank')
        }
      }).catch(err => {
        console.log(err)
      })
    },
    manufacturerDetail() {
      manufacturerDetail({ param: { manufacturerId: this.tabList[this.active].id }}, sessionStorage.getItem('venueId')).then(res => {
        if (res.errorCode === '000000') {
          const cont = res.record.manufacturer + res.record.text.replace(/\n/g, '<br/>')
          this.$alert(cont, '厂商说明', {
            dangerouslyUseHTMLString: true
          })
        }
      }).catch(err => {
        console.log(err)
      })
    },
    showTimeBtn(e) {
      this.showTime = true
      this.cameraIndexCode = e.id
      this.param = {}
    },
    cancelTime() {
      this.showTime = false
    },
    confirmTime() {
      if (!this.param.startTime) {
        this.$message.error('请选择开始时间')
        return
      }
      if (!this.param.endTime) {
        this.$message.error('请选择结束时间')
        return
      }
      var startTime = new Date(this.param.startTime).getTime()
      var endTime = new Date(this.param.endTime).getTime()
      if (endTime <= startTime) {
        this.$message.warning('结束时间不能早于开始时间')
        return
      }
      this.showTime = false
      this.add(1)
    },
    gbVideo() {
      this.showJk = false
      this.oWebControl.JS_HideWnd()
    },
    add(e, cont) {
      if (e === 0) {
        this.cameraIndexCode = cont.id
      }
      this.showJk = true
      this.playMode = e
      // 首次加载时的到父容器的高度
      setTimeout(() => {
        this.playWndHeight = this.$refs.playWndBox.clientHeight
        // 首次加载时的到父容器的宽度
        this.playWndWidth = this.$refs.playWndBox.clientWidth
        // 初始化摄像头
        this.$nextTick(() => {
          this.initPlugin()
        })
        // 监听resize事件，使插件窗口尺寸跟随DIV窗口变化
        window.addEventListener('resize', () => {
          if (this.oWebControl != null) {
            this.oWebControl.JS_Resize(
              this.$refs.playWndBox.clientWidth,
              this.$refs.playWndBox.clientHeight
            )
          }
        })
      }, 500)
    },
    huifan() {
      var cameraIndexCode = this.cameraIndexCode // 获取输入的监控点编号值，必填
      var startTimeStamp = new Date(this.param.startTime).getTime()
      var endTimeStamp = new Date(this.param.endTime).getTime()
      // var startTimeStamp = new Date($("#startTimeStamp").val()).getTime();    //回放开始时间戳，必填
      // var endTimeStamp = new Date($("#endTimeStamp").val()).getTime();        //回放结束时间戳，必填
      var recordLocation = 0 // 录像存储位置：0-中心存储，1-设备存储
      var transMode = 1 // 传输协议：0-UDP，1-TCP
      var gpuMode = 0 // 是否启用GPU硬解，0-不启用，1-启用
      var wndId = -1 // 播放窗口序号（在2x2以上布局下可指定播放窗口）

      this.oWebControl.JS_RequestInterface({
        funcName: 'startPlayback',
        argument: JSON.stringify({
          cameraIndexCode: cameraIndexCode, // 监控点编号
          startTimeStamp: Math.floor(startTimeStamp / 1000).toString(), // 录像查询开始时间戳，单位：秒
          endTimeStamp: Math.floor(endTimeStamp / 1000).toString(), // 录像结束开始时间戳，单位：秒
          recordLocation: recordLocation, // 录像存储类型：0-中心存储，1-设备存储
          transMode: transMode, // 传输协议：0-UDP，1-TCP
          gpuMode: gpuMode, // 是否启用GPU硬解，0-不启用，1-启用
          wndId: wndId // 可指定播放窗口
        })
      })
    },
    // 创建播放实例
    initPlugin() {
      const that = this
      this.oWebControl = null
      this.oWebControl = new WebControl({
        szPluginContainer: 'playWnd', // 指定容器id
        iServicePortStart: 15900, // 指定起止端口号，建议使用该值
        iServicePortEnd: 15909,
        // szClassId: '23BF3B0A-2C56-4D97-9C03-0CB103AA8F11', // 用于IE10使用ActiveX的clsid
        cbConnectSuccess: () => { // 创建WebControl实例成功
          that.oWebControl.JS_StartService('window', { // WebControl实例创建成功后需要启动服务
            // 值"./VideoPluginConnect.dll"写死
            dllPath: './VideoPluginConnect.dll'
          }).then(function() {
            // 设置消息回调
            that.oWebControl.JS_SetWindowControlCallback({
              cbIntegrationCallBack: that.cbIntegrationCallBack
            })
            // JS_CreateWnd创建视频播放窗口，宽高可设定
            that.oWebControl.JS_CreateWnd('playWnd', 1000, 600).then(function() {
              // 创建播放实例成功后初始化
              that.init()
            })
          }, function() {
            // 启动插件服务失败
          })
        },
        // 创建WebControl实例失败
        cbConnectError: function() {
          that.oWebControl = null
          that.$message.warning('插件未启动，正在尝试启动，请稍候...')
          // 程序未启动时执行error函数，采用wakeup来启动程序
          window.WebControl.JS_WakeUp('VideoWebPlugin://')
          that.initCount++
          if (that.initCount < 3) {
            setTimeout(function() {
              that.initPlugin()
            }, 3000)
          } else {
            that.$message.warning('插件启动失败，请检查插件是否安装！')
          }
        },
        cbConnectClose: () => {
          // 异常断开：bNormalClose = false
          // JS_Disconnect正常断开：bNormalClose = true
          console.log('cbConnectClose')
          that.oWebControl = null
        }
      })
    },
    // 初始化
    init(callback) {
      const that = this
      that.getPubKey(() => {
        const appkey = that.objData.appkey // 综合安防管理平台提供的appkey，必填
        const secret = that.setEncrypt(that.objData.secret) // 综合安防管理平台提供的secret，必填
        const ip = that.objData.ip // 综合安防管理平台IP地址，必填
        const playMode = that.playMode // 初始播放模式：0-预览，1-回放
        const port = that.objData.port // 综合安防管理平台端口，若启用HTTPS协议，默认443
        const snapDir = 'D:\\SnapDir' // 抓图存储路径
        const videoDir = 'D:\\VideoDir' // 紧急录像或录像剪辑存储路径
        const layout = '1x1' // playMode指定模式的布局
        const enableHTTPS = 1 // 是否启用HTTPS协议与综合安防管理平台交互，这里总是填1
        const encryptedFields = 'secret' // 加密字段，默认加密领域为secret
        const showToolbar = 1 // 是否显示工具栏，0-不显示，非0-显示
        const showSmart = 1 // 是否显示智能信息（如配置移动侦测后画面上的线框），0-不显示，非0-显示
        const buttonIDs = '0,16,256,257,258,259,260,512,513,514,515,516,517,768,769' // 自定义工具条按钮
        // var toolBarButtonIDs = "2049,2304" // 工具栏上自定义按钮
        that.oWebControl.JS_RequestInterface({
          funcName: 'init',
          argument: JSON.stringify({
            appkey: appkey, // API网关提供的appkey
            secret: secret, // API网关提供的secret
            ip: ip, // API网关IP地址
            playMode: playMode, // 播放模式（决定显示预览还是回放界面）
            port: port, // 端口
            snapDir: snapDir, // 抓图存储路径
            videoDir: videoDir, // 紧急录像或录像剪辑存储路径
            layout: layout, // 布局
            enableHTTPS: enableHTTPS, // 是否启用HTTPS协议
            encryptedFields: encryptedFields, // 加密字段
            showToolbar: showToolbar, // 是否显示工具栏
            showSmart: showSmart, // 是否显示智能信息
            buttonIDs // 自定义工具条按钮
          })
        }).then(function(oData) {
          that.oWebControl.JS_Resize(that.playWndWidth, that.playWndHeight) // 初始化后resize一次，规避firefox下首次显示窗口后插件窗口未与DIV窗口重合问题
          if (callback) {
            callback()
          }
          if (playMode === 1) {
            that.huifan()
          } else {
            that.previewVideo()
          }
          // 隐藏
          // that.oWebControl.JS_HideWnd()
        })
      })
    },
    // 获取公钥
    getPubKey(callback) {
      const that = this
      this.oWebControl.JS_RequestInterface({
        funcName: 'getRSAPubKey',
        argument: JSON.stringify({
          keyLength: 1024
        })
      }).then(function(oData) {
        if (oData.responseMsg.data) {
          that.pubKey = oData.responseMsg.data
          callback()
        }
      })
    },
    // RSA 加密
    setEncrypt(value) {
      const that = this
      const encrypt = new window.JSEncrypt()
      encrypt.setPublicKey(that.pubKey)
      return encrypt.encrypt(value)
    },
    // 回调的消息
    cbIntegrationCallBack(oData) {
      const { responseMsg: type } = oData
      if (type === 'error') {
        console.log(type, type, this.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'))
      } else {
        console.log(type, type, this.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'))
      }
    },
    // 视频预览功能
    previewVideo(data) {
      const that = this
      const cameraIndexCode = this.cameraIndexCode// 获取输入的监控点编号值，必填
      const streamMode = 0// 主子码流标识：0-主码流，1-子码流
      const transMode = 0// 传输协议：0-UDP，1-TCP
      const gpuMode = 0// 是否启用GPU硬解，0-不启用，1-启用
      const wndId = -1// 播放窗口序号（在2x2以上布局下可指定播放窗口）
      that.oWebControl.JS_RequestInterface({
        funcName: 'startPreview',
        argument: JSON.stringify({
          cameraIndexCode: cameraIndexCode, // 监控点编号
          streamMode: streamMode, // 主子码流标识
          transMode: transMode, // 传输协议
          gpuMode: gpuMode, // 是否开启GPU硬解
          wndId: wndId// 可指定播放窗口
        })
      })
    },
    // 停止全部预览
    stopAllPreview() {
      this.oWebControl.JS_RequestInterface({
        funcName: 'stopAllPreview'
      })
    },
    // 格式化时间
    dateFormat(oDate, fmt) {
      const o = {
        'M+': oDate.getMonth() + 1, // 月份
        'd+': oDate.getDate(), // 日
        'h+': oDate.getHours(), // 小时
        'm+': oDate.getMinutes(), // 分
        's+': oDate.getSeconds(), // 秒
        'q+': Math.floor((oDate.getMonth() + 3) / 3), // 季度
        'S': oDate.getMilliseconds()// 毫秒
      }
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (oDate.getFullYear() + '').substr(4 - RegExp.$1.length))
      }
      for (const k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
        }
      }
      return fmt
    }
  }
}
</script>

<style lang="scss" scoped>
.hksp {
  width: 100%;
  height: 70vh;
}
.xzsj {
  display: flex;
  align-items: center;
  .division-line {
    margin: 0 20px;
  }
}
.tips{
  display: flex;
  margin-bottom: 20px;
  .tips_box{
    flex: 1;
    display: flex;
    align-items: center;
    background-color: rgba(32, 178, 170, 1);
    &:first-of-type{
      margin-right: 10px;
    }
    &:last-of-type{
      margin-left: 10px;
      background-color: rgba(65, 105, 225, 1);
    }
    div {
      font-size: 20px;
      color: #fff;
      text-align: center;
      padding: 20px 0;
      line-height: 1.5;
      flex: 1;
      p{
        margin: 0;
        &:last-of-type{
          margin-top: 20px;
          font-size: 24px;
          font-weight: bold;
        }
      }
      &.tips_xian{
        width: 1px;
        height: 80px;
        background-color: #fff;
        flex: none;
      }
    }
  }
}
</style>
<style>
.rqtc .el-picker-panel__footer .el-button--text{
  display: none !important;
}
</style>
